import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:imclient/imclient.dart';
import 'package:imclient/model/conversation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wfc_example/app_server.dart';
import 'package:wfc_example/config.dart';
import 'package:wfc_example/messages/messages_screen.dart';


import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../http/api.dart';

class SingleChatPage extends StatefulWidget {
  const SingleChatPage({super.key, required this.uid});
  final String uid;
  @override
  State<SingleChatPage> createState() => _SingleChatPageState();
}

class _SingleChatPageState extends State<SingleChatPage> {
  @override
  late Conversation conversation;
  bool isLogin=false;
  void initState() {
    // TODO: implement initState
    super.initState();

    print(widget.uid);
    // ImInit();
    getIMToken();
    if(widget.uid!="")
      conversation = Conversation(conversationType: ConversationType.Single, target:"${widget.uid}");

  }
//4ygqmws2k
  //IMtoken
  Future<void> getIMToken() async {
  String? userId =await UserIdManager.getUserID();
    ApiManager.postData(
      context,
      'api/auth/auth/driver/doChatLogin',
      {
        "userId": userId,
        "clientId":await Imclient.clientId,
        'platform': 2,
      },
          (responseData) async {
            await IMIdManager.saveIMID(responseData['data']['imToken']);
            ImInit();
      },
    );
  }
 void ImInit()  async{

    String? phoneNum =await PhoneNumManager.getPhone();
    String? userIdstr =await UserIdManager.getUserID();
    String? imToken =await IMIdManager.getIMID();
    var result= Imclient.connect(Config.IM_Host, userIdstr!, imToken!);
    if (result.toString()=="0") {
      setState(() {
            isLogin=true;
          });
    }else{
      getIMToken();
    //   AppServer.login(
    //       phoneNum!, "66666", (userId, token, isNewUser) {
    //     Imclient.connect(Config.IM_Host, userId, token);
    //     setState(() {
    //       isLogin=true;
    //     });
    //   }, (msg) {
    //     Fluttertoast.showToast(msg: "登录失败");
    //   });
    }

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      body: Container(
        child: isLogin? MessagesScreen(conversation):Container(),
      ),
    );
  }
}
